// 通知系统 Store

import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Notification, NotificationOptions } from '@/types/notification'

export const useNotificationStore = defineStore('notification', () => {
  const notifications = ref<Notification[]>([])

  const addNotification = (options: NotificationOptions): string => {
    const id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
    
    const notification: Notification = {
      id,
      type: options.type || 'info',
      title: options.title,
      message: options.message,
      details: options.details,
      duration: options.duration ?? 5000, // 默认5秒
      persistent: options.persistent || false,
      actions: options.actions || [],
      createdAt: Date.now(),
      onClick: options.onClick
    }

    notifications.value.push(notification)

    // 自动移除非持久化通知
    if (!notification.persistent && notification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, notification.duration)
    }

    return id
  }

  const removeNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }

  const updateNotification = (id: string, updates: Partial<Notification>) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      Object.assign(notification, updates)
    }
  }

  const clearNotifications = () => {
    notifications.value = []
  }

  // 便捷方法
  const info = (title: string, message?: string, options?: Partial<NotificationOptions>) => {
    return addNotification({
      type: 'info',
      title,
      message,
      ...options
    })
  }

  const success = (title: string, message?: string, options?: Partial<NotificationOptions>) => {
    return addNotification({
      type: 'success',
      title,
      message,
      ...options
    })
  }

  const warning = (title: string, message?: string, options?: Partial<NotificationOptions>) => {
    return addNotification({
      type: 'warning',
      title,
      message,
      ...options
    })
  }

  const error = (title: string, message?: string, options?: Partial<NotificationOptions>) => {
    return addNotification({
      type: 'error',
      title,
      message,
      duration: 0, // 错误通知默认不自动关闭
      ...options
    })
  }

  return {
    notifications,
    addNotification,
    removeNotification,
    updateNotification,
    clearNotifications,
    info,
    success,
    warning,
    error
  }
})